/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import '../../base-ui/BaseElement';
import { BaseElement, element } from '../../base-ui/BaseElement';
import { SpDivChartTemp } from '../sub-template/SpDivChartTemp';
import { LitDoughnutChart } from '../../base-ui/chart/doughnut/LitDoughnutChart';
import '../../base-ui/chart/doughnut/LitDoughnutChart';
import { LitChartColumn } from '../../base-ui/chart/column/LitChartColumn';
import '../../base-ui/chart/column/LitChartColumn';
import { SpStatisticsHttpUtil } from '../util/SpStatisticsHttpUtil';
import { Rectangle } from '../../base-ui/chart/rectangular-tree/Rectangle';
import { RectangleCanvas } from '../../base-ui/chart/rectangular-tree/RectangleCanvas';
import { RectangleCanvasElement } from '../../base-ui/chart/rectangular-tree/RectangleCanvasElement';
import { LitChartPie } from '../../base-ui/chart/pie/LitChartPie';
import '../../base-ui/chart/pie/LitChartPie';
import { LitLineChart } from '../../base-ui/chart/lineChart/LitLineChart';
import { conversionChartPoints } from '../util/SpStatisticsGroupUtil';
import { GroupType } from '../util/SpStatisticsHttpBean';
import { LitDatePicker } from '../../base-ui/datepicker/LitDatePicker';
import { start } from 'repl';

@element('sp-visit-statistics-panel')
export class SpVisitStatisticsPanel extends BaseElement {
  private doughnutChart: LitDoughnutChart | undefined | null;
  private weeklyChart: LitChartColumn | undefined | null;
  private pageDistribution: SpDivChartTemp | undefined | null;
  private rowAndTabDistribution: SpDivChartTemp | undefined | null;
  private rectangleCanvas: RectangleCanvasElement | undefined;
  private pluginUseTemp: SpDivChartTemp | undefined | null;
  private pluginUseChart: LitChartPie | undefined | null;
  private docTemp: SpDivChartTemp | undefined | null;
  private docChart: LitLineChart | undefined | null;
  private queryTemp: SpDivChartTemp | undefined | null;
  private queryChart: LitLineChart | undefined | null;
  private downloadTemp: SpDivChartTemp | undefined | null;
  private downloadChart: LitLineChart | undefined | null;
  private metricsTemp: SpDivChartTemp | undefined | null;
  private metricsChart: LitLineChart | undefined | null;
  private hiperfTemp: SpDivChartTemp | undefined | null;
  private hiperfChart: LitLineChart | undefined | null;
  private convertSystraceTemp: SpDivChartTemp | undefined | null;
  private convertSystraceChart: LitLineChart | undefined | null;
  private traceAnalysisTemplate: SpDivChartTemp | null | undefined;
  private traceAnalysisChart: LitLineChart | null | undefined;
  private recordCmdTemp: SpDivChartTemp | null | undefined;
  private recordCmdChart: LitLineChart | null | undefined;
  private sevenPageSpan: HTMLSpanElement | null | undefined;
  private startTime: number = 0;
  private endTime: number = 0;
  private interVal: number = 0;
  private item: any;
  private treeCanvas: RectangleCanvas | null | undefined;
  private WidthRefresh: number | undefined;
  initElements(): void {
    this.intPageDistribution();
    this.initTraceAnalysis();
    this.initRowAndTabDistribution();
    this.initRecordCmd();
    this.initPluginUse();
    this.initOtherPages();
    this.WidthRefresh = window.innerWidth;

    new ResizeObserver((entries) => {
      //宽度变化，重新绘制矩形树图
      if (this.startTime > 0 && this.WidthRefresh != window.innerWidth) {
        this.treeCanvas!.areas = [];
        this.treeCanvas!.clear();
        this.treeCanvas!.clearAll();
        this.treeCanvas?.setWidth(window.innerWidth * 0.6);
        this.treeCanvas?.setHeight(window.innerHeight * 0.6);
        this.initRowAndTabData(this.startTime, this.endTime, this.interVal);
        this.WidthRefresh = window.innerWidth
      }
    }).observe(this);
  }

  connectedCallback() { }

  maps = {
    config_page: '配置页面',
    help_doc: 'Help文档',
    trace_row: 'trace分析页面',
    metrics: 'metrics页面',
    hiperf_func: '汇编指令',
    convertSystrace_func: '转换systrace',
    info_stats: 'infoStats页面',
    query: 'Query页面',
    scheduling_analysis: '调度分析',
  };

  colors = [
    '#3C53C9',
    '#FD7A5F',
    '#FDD761',
    '#7359C2',
    '#42C289',
    '#92E99E',
    '#2E8AE7',
    '#44C1EA',
    '#4Dd621',
    '#ff689b',
    '#fa5c8c',
    '#0acf98',
    '#02a8b4',
    '#39afd2',
    '#726cf5',
    '#6b4eae',
    '#51d59a',
    '#81a6fe',
    '#aa67f6',
    '#cc3fa2',
    '#ffba48',
    '#ff6664',
  ];

  intPageDistribution() {
    this.pageDistribution = this.shadowRoot?.querySelector<SpDivChartTemp>('#page_distribution_template');
    this.doughnutChart = this.shadowRoot?.querySelector<LitDoughnutChart>('#doughnut');
    this.weeklyChart = this.shadowRoot?.querySelector<LitChartColumn>('#weeklyColumn');
    this.sevenPageSpan = this.shadowRoot?.querySelector<HTMLSpanElement>('#seven_page_span');
    this.pageDistribution!.datePickerEl?.addEventListener('date_change', (ev: any) => {
      let detail = ev.detail;
      let startTimeStr = detail.startTime;
      let endTimeStr = detail.endTime;
      this.initPageDistributionData(startTimeStr, endTimeStr);
    });
    this.doughnutChart!.addEventListener('select', (ev: any) => {
      let detail = ev.detail.value;
      let endTimeStr = this.pageDistribution!.datePickerEl?.currentDateValue[1];
      let startTimeStr = SpStatisticsHttpUtil.getPreviousDate(6, endTimeStr);
      let startTime = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
      let endTime = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
      let request = {
        startTime: startTime,
        endTime: endTime,
        interval: SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime),
        action: detail.pageName,
      };
      let requestBody = {
        startTime: startTime,
        endTime: endTime,
        interval: GroupType.DAY,
      };
      SpStatisticsHttpUtil.getOrdinaryVisitData('pageUseRecord', request, (info: any) => {
        if (info.code == 0) {
          let chartData = conversionChartPoints(requestBody, {
            data: info.data,
          });
          this.weeklyChart!.dataSource = chartData['data'];
        }
      });
    });
  }

  initTraceAnalysis() {
    this.traceAnalysisTemplate = this.shadowRoot?.querySelector<SpDivChartTemp>('#trace_analysis_template');
    this.traceAnalysisChart = this.shadowRoot?.querySelector<LitLineChart>('#trace_analysis_chart');
    this.traceAnalysisTemplate!.datePickerEl?.addEventListener('date_change', (ev: any) => {
      let detail = ev.detail;
      let startTimeStr = detail.startTime;
      let endTimeStr = detail.endTime;
      let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
      let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
      let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
      this.initTraceAnalysisData(startTime, endTime, interVal);
    });
  }

  initRecordCmd() {
    this.recordCmdTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#record_cmd_template');
    this.recordCmdChart = this.shadowRoot?.querySelector<LitLineChart>('#record_cmd_chart');
    this.recordCmdTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
      let detail = ev.detail;
      let startTimeStr = detail.startTime;
      let endTimeStr = detail.endTime;
      let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
      let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
      let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
      this.initRecordCmdData(startTime, endTime, interVal);
    });
  }

  initPluginUse() {
    this.pluginUseTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#plugin_use_template');
    this.pluginUseChart = this.shadowRoot?.querySelector<LitChartPie>('#plugin_use_chart');
    this.pluginUseTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
      let detail = ev.detail;
      let startTimeStr = detail.startTime;
      let endTimeStr = detail.endTime;
      let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
      let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
      this.initPluginUseData(startTime, endTime);
    });
  }

  initOtherPages() {
    this.docTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#doc_template');
    this.docChart = this.shadowRoot?.querySelector<LitLineChart>('#docColumn');
    this.docTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
      let detail = ev.detail;
      let startTimeStr = detail.startTime;
      let endTimeStr = detail.endTime;
      let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
      let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
      let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
      this.initDocData(startTime, endTime, interVal);
    });
    this.queryTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#query_template');
    this.queryChart = this.shadowRoot?.querySelector<LitLineChart>('#queryColumn');
    this.queryTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
      let detail = ev.detail;
      let startTimeStr = detail.startTime;
      let endTimeStr = detail.endTime;
      let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
      let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
      let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
      this.initQueryData(startTime, endTime, interVal);
    });
    this.downloadTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#download_template');
    this.downloadChart = this.shadowRoot?.querySelector<LitLineChart>('#downloadColumn');
    this.downloadTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
      let detail = ev.detail;
      let startTimeStr = detail.startTime;
      let endTimeStr = detail.endTime;
      let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
      let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
      let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
      this.initDownloadData(startTime, endTime, interVal);
    });
    this.metricsTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#metrics_template');
    this.metricsChart = this.shadowRoot?.querySelector<LitLineChart>('#metricsColumn');
    this.metricsTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
      let detail = ev.detail;
      let startTimeStr = detail.startTime;
      let endTimeStr = detail.endTime;
      let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
      let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
      let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
      this.initMetricsData(startTime, endTime, interVal);
    });
    this.hiperfTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#hiperf_template');
    this.hiperfChart = this.shadowRoot?.querySelector<LitLineChart>('#hiperfColumn');
    this.hiperfTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
      let detail = ev.detail;
      let startTimeStr = detail.startTime;
      let endTimeStr = detail.endTime;
      let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
      let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
      let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
      this.initHiperfData(startTime, endTime, interVal);
    });
    this.convertSystraceTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#convertSystrace_template');
    this.convertSystraceChart = this.shadowRoot?.querySelector<LitLineChart>('#convertSystraceColumn');
    this.convertSystraceTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
      let detail = ev.detail;
      let startTimeStr = detail.startTime;
      let endTimeStr = detail.endTime;
      let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
      let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
      let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
      this.initConvertSystraceData(startTime, endTime, interVal);
    });
  }

  initRowAndTabDistribution() {
    this.rectangleCanvas = new RectangleCanvasElement();
    this.item = this.rectangleCanvas?.shadowRoot?.querySelector('#treemap');
    this.item!.setAttribute('width', window.innerWidth * 0.6 + '');
    this.item!.setAttribute('height', window.innerHeight * 0.6 + '');
    this.treeCanvas = new RectangleCanvas(this.item);
    let tip = this.rectangleCanvas?.shadowRoot?.querySelector('#tip');
    this.treeCanvas!.canvasMouseMoveEvent(tip);
    this.treeCanvas!.canvasMouseLeaveEvent(tip);
    this.rowAndTabDistribution = this.shadowRoot?.querySelector<SpDivChartTemp>('#row_tab_count_template');
    this.rowAndTabDistribution!.datePickerEl?.addEventListener('date_change', (ev: any) => {
      let detail = ev.detail;
      let startTimeStr = detail.startTime;
      let endTimeStr = detail.endTime;
      let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
      let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
      let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
      this.initRowAndTabData(startTime, endTime, interVal);
    });
  }

  getPageChName(pageName: string): string {
    // @ts-ignore
    let name = this.maps[pageName];
    if (name == null) {
      return '';
    }
    return name;
  }

  getColor(index: number) {
    return this.colors[index];
  }

  initWeeklyChart(pageInfo: any, startTs: number, endTs: number) {
    let requestBody = {
      startTime: startTs,
      endTime: endTs,
      interval: GroupType.DAY,
      action: pageInfo.pageName,
    };
    SpStatisticsHttpUtil.getOrdinaryVisitData('pageUseRecord', requestBody, (res: any) => {
      if (res.code == 0) {
        let chartData = conversionChartPoints(requestBody, {
          data: res.data,
        });
        if (chartData['data'].length > 0) {
          this.sevenPageSpan!.style.display = 'block';
        } else {
          this.sevenPageSpan!.style.display = 'none';
        }
        this.weeklyChart!.config = {
          data: chartData['data'],
          appendPadding: 10,
          xField: 'date',
          yField: 'value',
          seriesField: 'date',
          color: () => {
            return '#0a59f7';
          },
          tip: (a) => {
            if (a && a[0]) {
              let tip = '';
              tip = `<div>
                             <div>count:${a[0].obj.value}</div>
                                 ${tip}
                             </div>`;
              return tip;
            } else {
              return '';
            }
          },
          label: null,
          isRotate: true,
        };
      }
    });
  }

  initPageDistributionData(startTimeStr: string, endTimeStr: string) {
    let startTs: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
    let endTs: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
    SpStatisticsHttpUtil.getOrdinaryVisitData(
      'pageDistribution',
      {
        startTime: startTs,
        endTime: endTs,
      },
      (res: any) => {
        if (res.code === 0) {
          let pages: Array<any> = res.data.pages;
          let data: Array<any> = [];
          if (pages) {
            pages.forEach((page, index) => {
              let name = this.getPageChName(page.pageName);
              if (name.length > 0) {
                page.name = name;
                page.num = page.accessCount;
                page.color = this.getColor(index);
                data.push(page);
              }
            });
          }
          this.doughnutChart!.config = {
            title: 'SmartPerf页面访问分布',
            selectIndex: 0,
            data: data,
          };
          if (data.length > 0) {
            let startTime = SpStatisticsHttpUtil.getPreviousDate(6, endTimeStr);
            let weeklyStartTime = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTime);
            this.initWeeklyChart(data[0], weeklyStartTime, endTs);
          } else {
            this.weeklyChart!.dataSource = []
          }
        }
      }
    );
  }

  initTraceAnalysisData(startTs: number, endTs: number, intervalCode: number) {
    let requestBody = {
      startTime: startTs,
      endTime: endTs,
      interval: intervalCode,
    };
    SpStatisticsHttpUtil.getOrdinaryVisitData('importTrace', requestBody, (res: any) => {
      if (res.code === 0) {
        let chartData = conversionChartPoints(requestBody, res.data);
        this.traceAnalysisChart!.dataSource(chartData, {
          importTrace: 'trace解析数量',
        });
      }
    });
  }

  initRecordCmdData(startTs: number, endTs: number, intervalCode: number) {
    let requestBody = {
      startTime: startTs,
      endTime: endTs,
      interval: intervalCode,
    };
    SpStatisticsHttpUtil.getOrdinaryVisitData('commandUseRecord', requestBody, (res: any) => {
      if (res.code === 0) {
        let chartData = conversionChartPoints(requestBody, res.data);
        this.recordCmdChart!.dataSource(chartData, { offline: '离线抓取命令数', online: '在线抓取命令数' }, true);
      }
    });
  }



  initPluginUseData(startTs: number, endTs: number) {
    SpStatisticsHttpUtil.getOrdinaryVisitData(
      'requestPluginUsage',
      {
        startTime: startTs,
        endTime: endTs,
        interval: 3
      },
      (res: any) => {
        if (res.code === 0) {
          let pluginData: Array<any> = res.data.data;
          let data: Array<any> = [];
          let totalCount = 0;
          if (pluginData) {
            totalCount = pluginData.reduce((pre, cur) => {
              let isHasSamePlugin = data.some((item: any) => {
                return item.type === cur.type;
              })
              if (!isHasSamePlugin) {
                data.push(cur);
              } else {
                data.forEach(item => {
                  if (item.type === cur.type) {
                    item.value += cur.value;
                  }
                })
              }
              pre += cur.value;
              return pre;
            }, 0)
            data?.forEach((plug, index) => {
              plug.index = index;
              plug.proportion = Number((plug.value / totalCount * 100).toFixed(3)) + '%';
            });
            // @ts-ignore
            data = data.sort((a, b) => { return b.value - a.value });
          }
          this.pluginUseChart!.config = {
            appendPadding: 0,
            data: data || [],
            angleField: 'value',
            colorField: 'type',
            showChartLine: true,
            radius: 1,
            label: {
              type: 'outer',
              color: (it) => {
                // @ts-ignore
                return this.getColor(it!.index);
              },
            },
            tip: (obj) => {
              return `<div>
                                    <div>插件:${obj.obj.type}</div> 
                                    <div>使用数量:${obj.obj.value}</div>
                                </div>
                                `;
            },
            interactions: [
              {
                type: 'element-active',
              },
            ],
          };
        }
      }
    );
  }

  initDocData(startTs: number, endTs: number, intervalCode: number) {
    let requestBody = {
      startTime: startTs,
      endTime: endTs,
      interval: intervalCode,
      action: 'help_doc',
    };
    SpStatisticsHttpUtil.getOrdinaryVisitData('pageUseRecord', requestBody, (res: any) => {
      if (res.code == 0) {
        let chartData = conversionChartPoints(requestBody, {
          data: res.data,
        });
        this.docChart!.dataSource(chartData, {
          data: 'help文档使用量',
        });
      }
    });
  }

  initQueryData(startTs: number, endTs: number, intervalCode: number) {
    let requestBody = {
      startTime: startTs,
      endTime: endTs,
      interval: intervalCode,
      action: 'query',
    };
    SpStatisticsHttpUtil.getOrdinaryVisitData('pageUseRecord', requestBody, (res: any) => {
      if (res.code == 0) {
        let chartData = conversionChartPoints(requestBody, {
          data: res.data,
        });
        this.queryChart!.dataSource(chartData, {
          data: 'query使用量',
        });
      }
    });
  }

  initDownloadData(startTs: number, endTs: number, intervalCode: number) {
    let requestBody = {
      startTime: startTs,
      endTime: endTs,
      interval: intervalCode,
      action: 'download',
    };
    SpStatisticsHttpUtil.getOrdinaryVisitData('downLoadUseRecord', requestBody, (res: any) => {
      if (res.code == 0) {
        let chartData = conversionChartPoints(requestBody, res.data);
        this.downloadChart!.dataSource(
          chartData,
          {
            downLoadDB: '下载DB',
            downLoadFile: '下载文件',
          },
          true
        );
      }
    });
  }

  initMetricsData(startTs: number, endTs: number, intervalCode: number) {
    let requestBody = {
      startTime: startTs,
      endTime: endTs,
      interval: intervalCode,
      action: 'metrics',
    };
    SpStatisticsHttpUtil.getOrdinaryVisitData('pageUseRecord', requestBody, (res: any) => {
      if (res.code == 0) {
        let chartData = conversionChartPoints(requestBody, {
          data: res.data,
        });
        this.metricsChart!.dataSource(chartData, {
          data: 'metrics使用量',
        });
      }
    });
  }

  initHiperfData(startTs: number, endTs: number, intervalCode: number) {
    let requestBody = {
      startTime: startTs,
      endTime: endTs,
      interval: intervalCode,
      action: 'hiperf_func',
    };
    SpStatisticsHttpUtil.getOrdinaryVisitData('pageUseRecord', requestBody, (res: any) => {
      if (res.code == 0) {
        let chartData = conversionChartPoints(requestBody, {
          data: res.data,
        });
        this.hiperfChart!.dataSource(chartData, {
          data: '汇编指令功能使用量',
        });
      }
    });
  }

  initConvertSystraceData(startTs: number, endTs: number, intervalCode: number) {
    let requestBody = {
      startTime: startTs,
      endTime: endTs,
      interval: intervalCode,
      action: 'convert_systrace',
    };
    SpStatisticsHttpUtil.getOrdinaryVisitData('pageUseRecord', requestBody, (res: any) => {
      if (res.code == 0) {
        let chartData = conversionChartPoints(requestBody, {
          data: res.data,
        });
        this.convertSystraceChart!.dataSource(chartData, {
          data: '转换systrace使用量',
        });
      }
    });
  }

  initData() {
    let startStr = SpStatisticsHttpUtil.getPreviousDate(6);
    let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startStr);
    let endTimeStr: string = SpStatisticsHttpUtil.getToday();
    let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
    let dataPickerAttr = {
      datePickerType: 'rangeDate',
      direction: 'bottomLeft',
      dateType: 'date',
      defaultDateValue: `${startStr} ~ ${endTimeStr}`,
    };
    this.pageDistribution?.timeData(dataPickerAttr);
    this.traceAnalysisTemplate?.timeData(dataPickerAttr);
    this.rowAndTabDistribution?.timeData(dataPickerAttr);
    this.recordCmdTemp?.timeData(dataPickerAttr);
    this.pluginUseTemp?.timeData(dataPickerAttr);
    this.docTemp?.timeData(dataPickerAttr);
    this.queryTemp?.timeData(dataPickerAttr);
    this.downloadTemp?.timeData(dataPickerAttr);
    this.metricsTemp?.timeData(dataPickerAttr);
    this.hiperfTemp?.timeData(dataPickerAttr);
    this.convertSystraceTemp?.timeData(dataPickerAttr);
    this.initPageDistributionData(startStr, endTimeStr);
    this.initTraceAnalysisData(startTime, endTime, GroupType.DAY);
    this.initRowAndTabData(startTime, endTime, GroupType.DAY);
    this.initRecordCmdData(startTime, endTime, GroupType.DAY);
    this.initPluginUseData(startTime, endTime);
    this.initDocData(startTime, endTime, GroupType.DAY);
    this.initQueryData(startTime, endTime, GroupType.DAY);
    this.initDownloadData(startTime, endTime, GroupType.DAY);
    this.initMetricsData(startTime, endTime, GroupType.DAY);
    this.initHiperfData(startTime, endTime, GroupType.DAY);
    this.initConvertSystraceData(startTime, endTime, GroupType.DAY);
  }

  initRowAndTabData(startTs: number, endTs: number, intervalCode: number) {
    this.startTime = startTs;
    this.endTime = endTs;
    this.interVal = intervalCode;
    let result: Array<any> = [];
    let legendContainer = this.rectangleCanvas?.shadowRoot?.querySelector('#legendContainer') as HTMLElement;
    let rowNoData = [
      {
        label: 'no data',
        value: 1,
        data: [
          {
            label: 'no data',
            value: 1,
          },
        ],
      },
    ];
    SpStatisticsHttpUtil.getOrdinaryVisitData(
      'rowRecord',
      {
        startTime: startTs,
        endTime: endTs,
        interval: intervalCode,
      },
      (res: any) => {
        this.treeCanvas!.areas = [];
        this.treeCanvas!.clear();
        this.treeCanvas!.clearAll();
        if (res.code === 0) {
          if (!res.data) {
            this.drawTree(rowNoData, legendContainer);
            return;
          }
          let rowDatas: Array<any> = res.data.filter((v: any) => {
            return v.rowdata !== 'Process'
          });;
          let subDatas: Array<any> = [];
          SpStatisticsHttpUtil.getOrdinaryVisitData(
            'rowSubRecord',
            {
              startTime: startTs,
              endTime: endTs,
              interval: intervalCode,
            },
            (res: any) => {
              if (res.code === 0) {
                subDatas = res.data.filter(
                  (v: any) => {
                    return v.rowdata !== "Process"
                  }
                );
                rowDatas.forEach((rowType) => {
                  let subData = new Array();
                  subDatas.forEach((subType) => {
                    if (rowType.rowdata === subType.rowdata) {
                      let sub = {
                        label: subType.subtype,
                        value: subType.count,
                      };
                      subData.push(sub);
                    }
                  });
                  let rowData = {
                    label: rowType.rowdata,
                    value: rowType.count,
                    data: subData,
                  };
                  result.push(rowData);
                });
                this.drawTree(result, legendContainer);
              }
            }
          );
        } else {
          this.drawTree(rowNoData, legendContainer);
        }
      }
    );
  }

  drawTree(result: Array<any>, legendContainer: HTMLElement) {
    let data = JSON.parse(JSON.stringify(result));
    let rootRect = Rectangle.RectangleTreemap(
      data,
      this.treeCanvas!.width,
      this.treeCanvas!.height,
      0,
      0,
      '',
      0,
      Rectangle.colors[0],
      null
    );
    this.treeCanvas!.canvasMouseUpEvent(rootRect);
    rootRect.drawChildAreas(this.treeCanvas!);
    rootRect.areasAsRoot = rootRect.areas;
    if (legendContainer) {
      Rectangle.RectangleLegendContainer = legendContainer;
    }
    rootRect.drawLegendLabels();
    this.rowAndTabDistribution!.append(this.rectangleCanvas!);
  }

  clearStatisticsPanel() {
    this.shadowRoot?.querySelectorAll<SpDivChartTemp>('sp-div-chart-temp').forEach((chartTemp) => {
      let litDatePicker = chartTemp.shadowRoot?.querySelector<LitDatePicker>('lit-datepicker');
      if (litDatePicker) {
        litDatePicker.clearDatePickerContent();
      }
    });
  }

  initHtml(): string {
    return `<style>
        :host{
           width: 100%;
           height: 100%;
        }
        .charts {
            padding: 1% 2%;  
            height: 66%;
        }
       
        #doughnut{
            height: 500px;
            width: 30%; 
            min-width: 145px;
            min-height: 300px;
        }
        #weeklyColumn{
            height: 420px;
        }
        .page_distribution{
            display: flex;
            align-items: center;
            justify-content: space-around;
            width: 100%;
            height: 100%;
            margin-top: 10px;
        }
        #plugin_use_div{
             width: 100%;
             height: 100%;
             display: flex;
             align-items: center;
             justify-content: center;
        }
        #plugin_use_chart,#detect_type_chart {
             width: 50%;         
             height: 500px; 
        }
        #other_pages_div{
            display: flex;
            flex-wrap:wrap;
            justify-content:space-between;
            align-items:center;
        }
        .trace_analysis{
            height: 400px;
        }
        .column{
            height: 300px;
        }
        .title {
          opacity: 0.8;
          color: #000000;
          text-align: center;
          font: 25px PingFangSC-Regular; 
          overflow: hidden;
        }
        #seven_page_span{
           display: none;
        }
        #record_cmd_chart{
           height: 400px;
        }
        </style>
        <div class="visit-panel">
            <div class="visit-head"></div>
            <div class="visit-content">
                <div class="charts">
                    <sp-div-chart-temp id="page_distribution_template">
                        <div class="page_distribution">
                           <lit-doughnut-chart id="doughnut"></lit-doughnut-chart>
                           <div style="width: 28%;">
                             <span class="title" id="seven_page_span">近7日页面使用量</span>
                             <lit-chart-column id="weeklyColumn"></lit-chart-column>
                           </div>
                        </div>
                    </sp-div-chart-temp>
                    <sp-div-chart-temp id="trace_analysis_template">
                        <span class="title">trace解析统计图</span>
                        <lit-line-chart class="trace_analysis" id="trace_analysis_chart"></lit-line-chart>
                    </sp-div-chart-temp>
                    
                    <sp-div-chart-temp id="row_tab_count_template">
                     <span class="title">各个泳道使用次数的占比图</span>
                     <br>
                     <br>
                        <div class="page_distributions">
                        </div>
                    </sp-div-chart-temp>
                      <sp-div-chart-temp id="record_cmd_template">
                        <span class="title">抓取命令数量统计</span>
                        <lit-line-chart id="record_cmd_chart"></lit-line-chart>
                    </sp-div-chart-temp>
                    
                    <sp-div-chart-temp id="plugin_use_template">
                        <span class="title">统计各个插件使用占比</span>
                        <div id="plugin_use_div">
                           <lit-chart-pie id="plugin_use_chart"></lit-chart-pie>
                        </div>
                    </sp-div-chart-temp>
                    <div id="other_pages_div">
                        <sp-div-chart-temp id="doc_template">
                           <span class="title">help文档使用数量统计</span>
                           <lit-line-chart class="column" id="docColumn"></lit-line-chart>
                        </sp-div-chart-temp>
                        <sp-div-chart-temp id="query_template">
                           <span class="title">query使用数量统计</span>
                           <lit-line-chart class="column" id="queryColumn"></lit-line-chart>
                        </sp-div-chart-temp>
                        <sp-div-chart-temp id="download_template">
                           <span class="title" >download使用数量统计</span>
                           <lit-line-chart class="column" id="downloadColumn"></lit-line-chart>
                        </sp-div-chart-temp>
                        <sp-div-chart-temp id="metrics_template">
                           <span class="title" >metrics使用数量统计</span>
                           <lit-line-chart class="column" id="metricsColumn"></lit-line-chart>
                        </sp-div-chart-temp>
                        <sp-div-chart-temp id="hiperf_template">
                           <span class="title" >汇编指令功能使用数量统计</span>
                           <lit-line-chart class="column" id="hiperfColumn"></lit-line-chart>
                        </sp-div-chart-temp>
                        <sp-div-chart-temp id="convertSystrace_template">
                           <span class="title" >转换systrace使用数量统计</span>
                           <lit-line-chart class="column" id="convertSystraceColumn"></lit-line-chart>
                        </sp-div-chart-temp>
                    </div>    
                </div>

            </div>
        </div>
        `;
  }
}
